package com.picket.service;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.picket.domain.EmailEnvelope;

public class EmailerService {

	
	public void sendEmail(EmailEnvelope email){
	        Properties props = new Properties();
	        Session session = Session.getDefaultInstance(props, null);

	        try {
	            Message msg = new MimeMessage(session);
	            msg.setFrom(new InternetAddress(email.getFromAddress()));
	            msg.addRecipients(Message.RecipientType.TO,
	                             getInternetAddresses(email.getToAddress().split(",")));
	            msg.setSubject(email.getSubject());
	            
	            Multipart mp = new MimeMultipart();

	            MimeBodyPart htmlPart = new MimeBodyPart();
	            htmlPart.setContent(email.getMessageBody(), "text/html");
	            mp.addBodyPart(htmlPart);
	            msg.setContent(mp);
	            
	            Transport.send(msg);

	        } catch (AddressException e) {
	            e.printStackTrace();
	        } catch (MessagingException e) {
	            e.printStackTrace();
	        } catch (Exception e){
	        	e.printStackTrace();
	        }
	}
	
	private InternetAddress[] getInternetAddresses(String[] addresses) throws AddressException{
		InternetAddress[] inetAddresses = new InternetAddress[addresses.length];  
		for(int i=0;i < addresses.length;i++){
			inetAddresses[i]= new InternetAddress(addresses[i]); 
		}
		return inetAddresses;
	}
}
